//
//  BPPayViewController.m
//  BabyPhotograph
//
//  Created by cesh on 2017/1/12.
//  Copyright © 2017年 cesh. All rights reserved.
//

#import "BPPayViewController.h"
#import "BPPaySelectView.h"
#import "UILabel+BPBoundingRect.h"
#import "BPAddressViewController.h"
#import "BPCouponViewController.h"
#import <UIImageView+WebCache.h>
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "RSADataSigner.h"

@interface BPPayViewController () <AddressProtocol, CouponProtocol, PaySelectViewProtocol>

@property (weak, nonatomic) IBOutlet UILabel *finalPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *originalPriceLabel;
@property (weak, nonatomic) IBOutlet UIButton *goPayBtn;
@property (weak, nonatomic) IBOutlet UITextField *name;

@property (weak, nonatomic) IBOutlet UIView *addressView;
@property (strong, nonatomic) UILabel *address;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintHeight;

@property (weak, nonatomic) IBOutlet UIImageView *comboImg;
@property (weak, nonatomic) IBOutlet UILabel *comboTitle;
@property (weak, nonatomic) IBOutlet UILabel *comboDesc;
@property (weak, nonatomic) IBOutlet UILabel *photographer;
@property (weak, nonatomic) IBOutlet UILabel *time;
@property (weak, nonatomic) IBOutlet UILabel *price;
@property (weak, nonatomic) IBOutlet UIView *couponView;
@property (weak, nonatomic) IBOutlet UILabel *couponLbl;
//订单ID
@property (copy, nonatomic) NSString *orderID;
//地址ID
@property (copy, nonatomic) NSString *addressID;
//优惠券ID
@property (copy, nonatomic) NSString *couponID;

@end

@implementation BPPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    self.title = @"提交订单";
    _goPayBtn.layer.cornerRadius = 4.0;
    
    NSLog(@"预约订单 %@", self.data);
    self.orderID = self.data[@"orderNo"];
    //判断是否有默认地址的情况
    NSArray *address = self.data[@"address"];
    if ([address count] > 0) {
        self.addressID = self.data[@"address"][@"id"];
    }
    
    //判断是否有优惠券
    NSDictionary *coupon = self.data[@"useCoupon"];
    if ([coupon count] > 0) {
        self.couponID = self.data[@"useCoupon"][@"id"];
    }
    
    [self setupUI];
}

//根据label的长度得到高度
- (CGFloat)heightForAddressLbl:(NSString *)addressString {
    //取得文字Lbl的高度
    UILabel *comment =[[UILabel alloc]initWithFrame:CGRectMake(80, 50, screenW - 90, 0)];
    comment.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    
    comment.text = addressString;
    
    CGRect myRect = [comment boundingRectWithInitSize:comment.frame.size];
    
    CGFloat height = myRect.size.height;
    
    return height;
}

- (void)setupUI {
    
    UILabel *addressLbl = [[UILabel alloc]initWithFrame:CGRectMake(80, 15, screenW - 90, 0)];
    self.address = addressLbl;
    //根据是否有默认地址来设置
    NSDictionary *address = self.data[@"address"];
    addressLbl.numberOfLines = 0;
    addressLbl.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    addressLbl.textColor = [UIColor colorWithRed:185/255.0 green:198/255.0 blue:208/255.0 alpha:1/1.0];
    
    if(address.count == 0) {
        addressLbl.text = @"点击选择";
        [addressLbl sizeToFit];
        self.constraintHeight.constant = 100;
    }
    else {
        //取得地址Lbl的frame
        NSString *addressString = [NSString stringWithFormat:@"%@ %@", address[@"local"], address[@"local_ext"]];
        addressLbl.text = addressString;
        CGRect myRect = [addressLbl boundingRectWithInitSize:addressLbl.frame.size];
        addressLbl.frame = CGRectMake(80, 15, screenW - 90, myRect.size.height);
        self.constraintHeight.constant = 50 + myRect.size.height + 30;
    }
    [self.addressView addSubview:addressLbl];
    
    [self.addressView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseAddress)]];
    [self.couponView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseCoupon)]];
    
    [self.comboImg sd_setImageWithURL:[NSURL URLWithString:self.data[@"packageInfo"][@"imgs"][0]] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
    self.comboTitle.text = self.data[@"packageInfo"][@"title"];
    self.comboDesc.text = self.data[@"packageInfo"][@"desc"];
    self.photographer.text = self.data[@"photographer"][@"name"];
    self.price.text = [NSString stringWithFormat:@"¥ %@",self.data[@"packageInfo"][@"price"]];
    self.originalPriceLabel.text = [NSString stringWithFormat:@"¥ %@",self.data[@"packageInfo"][@"price"]];
    NSUInteger length = [_originalPriceLabel.text length];
    
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:_originalPriceLabel.text];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
    
    [_originalPriceLabel setAttributedText:attri];
    
    self.time.text = self.data[@"time_str"];
    NSDictionary *userCoupon = self.data[@"useCoupon"];
    //有默认的优惠券可用
    if (userCoupon.count > 0) {
        self.couponLbl.text = [NSString stringWithFormat:@"%@ ¥%@", userCoupon[@"title"], userCoupon[@"money"]];
        CGFloat orinal = [self.data[@"packageInfo"][@"price"] floatValue];
        CGFloat coupon = [userCoupon[@"money"] floatValue];
        self.finalPriceLabel.text = [NSString stringWithFormat:@"¥ %.2f",orinal - coupon];
    }
    //无优惠券可用
    else {
        self.couponLbl.text = @"暂无优惠券可用";
        self.finalPriceLabel.text = [NSString stringWithFormat:@"¥ %@",self.data[@"packageInfo"][@"price"]];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.alpha = 1.0;
}
- (IBAction)clickPayBtn:(id)sender {
    //拦截用户未填写预约人的情况
    if (self.name.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请填写预约人姓名"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    //拦截用户没有默认地址的情况
    if (self.addressID == nil) {
        [SVProgressHUD showInfoWithStatus:@"请填写服务地址"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    BPPaySelectView *view = [[[NSBundle mainBundle]loadNibNamed:@"BPPaySelectView" owner:nil options:nil]lastObject];
    view.delegate = self;
    view.frame = [UIScreen mainScreen].bounds;
    
    [self.view addSubview:view];
}

- (void)chooseAddress {
    BPAddressViewController *addressVC = [[BPAddressViewController alloc]init];
    addressVC.delegate = self;
    [self.navigationController pushViewController:addressVC animated:YES];
}

- (void)chooseCoupon {
    BPCouponViewController *couponVC = [[BPCouponViewController alloc]init];
    couponVC.delegate = self;
    [self.navigationController pushViewController:couponVC animated:YES];
}

#pragma mark - Address Protocol 代理方法
- (void)selectedAddress:(NSDictionary *)addressData {
    NSLog(@"地址 %@", addressData);
    self.addressID = addressData[@"id"];
    [self.address removeFromSuperview];
    UILabel *addressLbl = [[UILabel alloc]initWithFrame:CGRectMake(80, 15, screenW - 90, 0)];
    self.address = addressLbl;
    addressLbl.numberOfLines = 0;
    addressLbl.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    addressLbl.textColor = [UIColor colorWithRed:185/255.0 green:198/255.0 blue:208/255.0 alpha:1/1.0];
    
    //取得地址Lbl的frame
    NSString *addressString = [NSString stringWithFormat:@"%@ %@", addressData[@"local"], addressData[@"local_ext"]];
    addressLbl.text = addressString;
    CGRect myRect = [self.address boundingRectWithInitSize:addressLbl.frame.size];
    addressLbl.frame = CGRectMake(80, 15, screenW - 90, myRect.size.height);
    self.constraintHeight.constant = 50 + myRect.size.height + 30;
    [self.addressView addSubview:addressLbl];
}

#pragma mark - Coupon Protocol 代理方法
- (void)selectedCoupon:(NSDictionary *)couponData {
    NSLog(@"优惠券 %@", couponData);
    self.couponID = couponData[@"id"];
    self.couponLbl.text = [NSString stringWithFormat:@"%@ ¥%@", couponData[@"title"], couponData[@"money"]];
}

#pragma mark - Pay Select View Protocol 代理方法
- (void)alipayTheBill {
    //支付宝支付
    // 1.设置partner/seller/privateKey
    // partner商户ID seller:卖家ID privateKey:私钥
    NSString *partner = @"2088121820533203";
    NSString *seller = @"yeyeahapp@163.com";
    NSString *privateKey = @"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCGeqkKHBM2S7mDx+tkxJwYHLVNrVdpiJPp6P2JgzH+vfh7Eb1d+Onwp563NTSWVreJbWMk2Bmd2ecd9R5ECoHXaAD/H7Nos0xoVs/XnZqhPV1E78RoRMepbtCfkF3RcrjnpMnbW240g7dmRJNDIz+xE5xmSqlWbpfjy9JXr5jq73bS0jvyCEmMzQgk+BZV45WjFN6a8jzbTG6cKMUQGm1S5oMk21qpqjyfGsQMpQlzgpeWvZoBlpfQNHgked7FZ3jXKmvNTSx6q6xNdl+L/xW/gnxn/fML8yoVznLvMIhkJPUNMdwv5CW2EzgUB+EoGeZmzHDPvnzV6vTeLtrener1AgMBAAECggEAYkILcuySiRCJSyVu9CDH4MJRIqFuBhkZ4kYvwiMPC4+ol9udXqU54XHIARsqAlL4Jby8PTZ8eR62xOfNpm968XX3jHGQOAcR5AbSNDveuMNKe80o1/qxXDYwzvW/5wKI4hBAwTsr6cj33wxqARsnNW4bz43r7tA9wN6zIQiXlcg03tqctpFZdQAU2zlYg5vPSPOfOY0GoqtG6GUebJLf+FMa6KsFq/ES4qypLU558FCPr9GDoRE+gkcnAv1mKb0KR1GkkXy2KCMty0AXNZhHaiHES7aJgNZO1I1+SujncmEc+JgBSN2fG4HCltFOecofywB/sICk9yPy3fnyiBnDAQKBgQDAFD8cARV/0oHbZUXmpk/IpDUGSM7mgU9L/b+V360+i7GGtEqNIgRaL8WjHQjzBPkYm4CSk2wQDsUQWz1QzgAZ69OXAYqPPmJCyLFKR7NPZ00cmPbSoO+Lk/yc3UNu3symU5RrXdYDYAdqTh91jk0zi7sgcAyV/phi3P6Ph5MpNQKBgQCzO1BLguRzE1jIEDPXoToAj3d17JeSdxU+RVKXrl/pI2Pdez4EGn3oME3PglIFV16dVxFoT1zCcrcNiCEIJBzMH33AcqTVLwVs+E5SSLLXzucOa/xxonXBd13BmlOazhu5IYG3XRJJyNxNhXoMMsgWUI7oPH6AXLAXIRsp45GywQKBgDXZNzwdna5hEKC2Spt4AqQITQk+/ionFFkEgWJ9+66uMQ3Hm6LnZ3r1K54n9KtUuJTKe4gcJk52JY8JVS5DIkoiEAakmvi/j4KTiwh9A2r+VeLvizrPfXiO+2Hqsg3yDkOO6OwUuXvmvw1xa2Zkh4Ys5UAZyZ1/a69Dr2YDpyEFAoGABKpkmrKbk8tLIloZn2FZCy6w42b3Qx7KdMaFMeGeKYl8TgWpRZ4S7Ppk7CPuUqlFkz7y+w4l0gH+deG3Smj2PvIK6fmSBOKmd4G3ODkgPrHqHdv9xE+AVTrwO9vylTMMUbNnlwhbM4SBB5uT48Fmp/4M2krI2DqRcuivtlVwM4ECgYEAinEWn4JowVhWqfN7U9hPDMSPer3aO8FgHZrB9HpolGCkEiBZbWiZbGvHv5cQsiw6Do7WvKrYmysk9AcQqWnCN/WBJOxbBCg4/0C0xP869ZdQorkp3+Voa+ThR1Y++089SVxAVxOPw6gQ5702AlpG/hLVE2j+f8GFrHATXjb/NjA=";
    
    // 2.生成订单
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    // 订单ID(由一定的算法生成的订单ID)
    order.tradeNO = self.orderID;
    
    // 2.1设置商品名
    order.productName = @"商品名称";
    // 2.2设置商品描述
    order.productDescription = @"商品描述";
    // 2.3设置商品价格
    order.amount = @"0.01";
    
    // 3.设置回调地址(由后台开发人员生成后提供)
    order.notifyURL = nil;
    
    // 4.设置固定值
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1.0";
    order.inputCharset = @"utf-8";
    order.itBPay = @"15m";
    order.showUrl = @"m.alipay.com";
    
    // 5.应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"jingdong";
    
    // 6.将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    
    // 7.获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    // 8.将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
        }];
    }
}

@end
